# coding:utf-8
# py2
import commands
import sys

from crawler.danmaku_density import convert_cid, count_ep_dense
from crawler.video_download import get_download_list, download_mp4

sys.path.append('/Users/lingzhengxin/workspace/python/Gunbaster')
sys.path.append('../..')
# 单话ep
if __name__ == '__main__':

    root_path = '/Users/lingzhengxin/Documents'
    gif_LW = '640x400'
    epid = 269674
    # filtered_key_word = ['完结', '撒花', '诈尸', '有生之年', '咚', '氪金', '考古', '会员', '富贵', '留念']
    filtered_key_word = ['完结', '撒花', '诈尸', '有生之年', '咚']

    # seasonid = 123
    # epid = 259772
    # epid = 267858
    density_seconds = 5
    # epid转cid
    ep = convert_cid(epid=epid)
    # 调用弹幕列表接口计算n秒内的最高弹幕密度
    ffmpeg_param = count_ep_dense(ep['cid'], density_seconds, ep['badge'], filtered_key_word)

    # 根据cid下载视频
    name = str(epid) + '，' + str(ep['index'])
    vedio_path = root_path + '/%s.mp4' % (name)
    result = get_download_list(ep['cid'])
    # 取下载清晰度最高的mp4视频的url地址
    largest_format_index = 0
    index = 0
    for info in result[u'info']:
        if info[u'format'] > largest_format_index:
            largest_format_index = index
        index += 1
    download_url = result[u'info'][largest_format_index][u'url']
    download_mp4(name, download_url, vedio_path)

    # 转制gif
    shell_command = 'ffmpeg -i %s %s -s %s -pix_fmt rgb24 %s -y' % (
        vedio_path, ffmpeg_param, gif_LW, vedio_path.replace('.mp4', '.gif'))
    (status, output) = commands.getstatusoutput(shell_command)
    print status, output
    shell_command = 'convert %s -fuzz %s -layers Optimize %s' % (
        vedio_path.replace('.mp4', '.gif'), '15%', vedio_path.replace('.mp4', 'fuzz.gif'))
    (status, output) = commands.getstatusoutput(shell_command)
    print status, output
